package com.lcq.practice.springboot.universal.demo.test_jdbc;

import org.junit.jupiter.api.Test;

import java.sql.*;

/**
 * @ClassName JdbcTest
 * @Description
 * @Author lichuanqi
 * @Date 2022/2/11 11:06
 * @Version 1.0
 **/
public class JdbcPreparedStatementTest {
    @Test
    public void test1(){
//        try {
//            //1、什么时候需要如此加载
//            Class.forName("com.mysql.cj.jdbc.Driver");
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }

        String url = "jdbc:mysql://lcq.dbserver.com:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String userName = "root";
        String password = "123456";
        Connection connection = null;
        PreparedStatement stm = null;
        ResultSet resultSet = null;
        try {
            connection = DriverManager.getConnection(url, userName, password);
            stm = connection.prepareStatement("SELECT * FROM user WHERE id = ?");
            stm.setString(1, "1");
            resultSet = stm.executeQuery();
            while(resultSet.next()){
                int row = resultSet.getRow();
                System.out.println("row:"+row);
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();

                for (int i = 1; i <= columnCount; i++){
                    String string = resultSet.getString(i);
                    String columnName = metaData.getColumnName(i);
                    System.out.print(columnName+":");
                    System.out.print(string+" ");
                }
                System.out.println();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (stm != null){
                try {
                    stm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
